<template>
	<view>
		<view class="yjuser">
			<!-- <view class="userimg">
				<up-upload :fileList="fileList1" @delete="deletePic" @afterRead="afterRead" :maxCount="1"></up-upload>
			</view> -->
			<view class="userimg">
				<image v-if="!userInfo.avatar" @click="handleImage" src="../../static/logo.png" mode=""></image>
				<button v-else type="balanced" open-type="chooseAvatar" @chooseavatar="handleImage">
					<u-avatar :src="avatar || userInfo.avatar" size="60"></u-avatar>
				</button>
			</view>
			<view class="namebox">
				<view class="">真 实 姓 名</view>
				<view class="xiqngq" @click="gotoname('real')">{{userInfo.realname}}<up-icon name="arrow-right"></up-icon></view>
			</view>
			<view class="namebox">
				<view class="">会 员 昵 称</view>
				<view class="xiqngq" @click="gotoname('nick')">{{userInfo.nickname}}<up-icon name="arrow-right"></up-icon></view>
			</view>
			<!-- <view class="namebox">
				<view class="">姓名</view>
				<view class="xiqngq">
					<input type="text" v-model="userInfo.realname" placeholder="请输入" />
				</view>
			</view> -->
			<view class="namebox">
				<view class="">手 机 号 码</view>
				<view class="xiqngq" @click="gotophone">{{userInfo.mobile}} <up-icon name="arrow-right"></up-icon></view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import { ref,onMounted } from 'vue';
	import{onShow} from '@dcloudio/uni-app'
	import request from '../../utils/request';
	const fileList1 = ref([]);
	let token= ref()
	onShow(()=>{
		token.value=uni.getStorageSync('token')
		getUserInfo()
		const userinfo = uni.getStorageSync('userinfo')
		name.value=userinfo.nickname
		phone.value=userinfo.mobile
		if(uni.getStorageSync("name")!=''){
			name.value=uni.getStorageSync("name")
		}
		if(uni.getStorageSync("phone")!=''){
			phone.value=uni.getStorageSync("phone")
		}
	})
	let name=ref('微信用户')
	let phone=ref('未添加')
	let userInfo=ref({})
	let avatar = ref('')
	
	const gotoname=(text)=>{
		uni.navigateTo({
			url:'/pages/myname/myname?text=' + text
		})
	}
	const gotophone=()=>{
		uni.navigateTo({
			url:'/pages/myphone/myphone?status=1'
		})
	}
	const afterRead = async (event) => {
	  // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
	  let lists = [].concat(event.file);
	  let fileListLen = fileList1.value.length;
	
	  // 更新 UI 状态为“上传中”
	  lists.forEach((item, index) => {
	    fileList1.value.push({
	      ...item,
	      status: 'uploading',
	      message: '上传中',
	    });
	  });
	
	  for (let i = 0; i < lists.length; i++) {
	    try {
	      const result = await uploadFilePromise(lists[i].url);
	
	      // 更新上传成功的文件状态
	      fileList1.value[fileListLen + i] = {
	        ...fileList1.value[fileListLen + i],
	        status: 'success',
	        message: '',
	        url: result, // 确保这里使用的是实际返回的 URL 或其他信息
	      };
	    } catch (error) {
	      // 更新上传失败的文件状态
	      fileList1.value[fileListLen + i] = {
	        ...fileList1.value[fileListLen + i],
	        status: 'fail',
	        message: '上传失败，请重试',
	      };
	      console.error('Failed to upload file:', error);
	    }
	  }
	};
	const deletePic = (event) => {
	  fileList1.value.splice(event.index, 1);
	};
	const uploadFilePromise = (url) => {
	  return new Promise((resolve, reject) => {
	    uni.uploadFile({
	      url: 'https://lanqiu.changgongwang.cn/api/common/upload',
	      filePath: url,
	      name: 'file',
	      formData: {},
	      header: {
	        "token": token.value
	      },
	      success: (res) => {
	        console.log('Upload Success:', res);
			let tempPath = JSON.parse(res.data)
	        resolve(res.data.data); // 假设返回的数据是新的文件 URL 或其他信息
			editInfo(tempPath.data.url)
	      },
	      fail: (err) => {
	        console.error('Upload Failed:', err);
	        reject(err);
	      }
	    });
	  });
	};
	
	const handleImage = (e) => {
		uni.showLoading({
			title: '加载中'
		});
		uni.uploadFile({
			url: 'https://lanqiu.changgongwang.cn/api/common/upload',
			filePath: e.detail.avatarUrl,
			name: 'file',
			header: {
			  "token": token.value
			},
			formData: {},
			success: uploadFileRes => {
				console.log(uploadFileRes)
				let data = JSON.parse(uploadFileRes.data)
				avatar.value = data.data.fullurl
				editInfo(data.data.url)
			},
			fail: (error) => {
				console.log(error)
				uni.showToast({
					title: '上传失败',
					duration: 2000
				});
			},
			complete: () => {
				uni.hideLoading();
			}
		});
	}
	
	const getUserInfo = () => {
		request.post('user/index', {header:{
				"token":token.value
			}}).then(res=>{
			userInfo.value = res.data
			fileList1.value = [res.data.avatar]
			uni.setStorageSync("userinfo",res.data)
		}).catch(err=>{
			console.log(err);
		})
	};
	
	const editInfo = (avatar) => {
		request.post('user/profile',{header:{
				"token":token.value
			}, data:{
			nickname:name.value,
			avatar:avatar
		}}).then(res=>{
			uni.$u.toast(res.msg)
			setTimeout(() => {
				uni.navigateBack()
			}, 1200)
		}).catch(err=>{
			console.log(err);
		})
	}
</script>

<style scoped lang="scss">
	.yjuser{
		width: 100%;
		height: 560rpx;
		box-sizing: border-box;
	} 
	.userimg{
		width: 160rpx;
		height: 160rpx;
		margin: 0 auto;
		margin-top: 150rpx;
		margin-bottom: 120rpx;
		border-radius: 50%;
		
		image {
			width: 100%;
			height: 100%;
		}
	}
	.imguplo{
		border-radius: 50%;
	}
	.namebox{
		width: 100%;
		height: 100rpx;
		display: flex;
		align-items: center;
		padding: 0 28rpx;
		box-sizing: border-box;
		justify-content: space-between;
	}
	.xiqngq{
		display: flex;
		align-items: center;
		
		input {
			text-align: right;
		}
	}
	
	button {
		padding: 0 !important;
		margin: 0 !important;
		background-color: transparent;
		width: 100%;
		height: 100%;
		
		&::after {
			border: 0 !important;
		}
	}
</style>
